package com.demo.apply.task;

import com.demo.apply.service.ApiService;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class VisitWebSiteTask {
    @Autowired
    ApiService service;
    //3.添加定时任务(每五分钟执行)
    @Scheduled(cron = "0 */5 * * * ?")

    private void configureTasks() {
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
        Date createTime=new Date();
//        使用httpClient访问网站
        CloseableHttpResponse response=null;
        try {
            //1.获得一个httpclient对象
            CloseableHttpClient httpclient = HttpClients.createDefault();
//2.生成一个get请求
            HttpGet httpget = new HttpGet("https://fuwu.most.gov.cn/");
//3.执行get请求并返回结果
          response  = httpclient.execute(httpget);
            //4.处理结果
//            获取状态码
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
            Date responseTime=new Date();
            Map param=new HashMap();
            param.put("status",statusCode);
            param.put("createtime",createTime);
            param.put("responsetime",responseTime);
            service.addVisitLog(param);
        } catch (Exception e) {
            e.printStackTrace();
        }finally
         {
            try {
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }
}
